//
//  WSPurchaseManager.m
//  CharonTVProject
//
//  Created by karong on 2023/8/10.
//

#import "WSPurchaseManager.h"
#import <StoreKit/StoreKit.h>
#import "WSGoods.h"
#import "WSPurchaseRequest.h"
#import <AppsFlyerLib/AppsFlyerLib.h>

@interface WSPurchaseManager () <SKProductsRequestDelegate, SKPaymentTransactionObserver, SKRequestDelegate>

// 用戶是否使用还原功能
@property (nonatomic, assign) BOOL isRestore;
// 还原订单用的原始ID
@property (nonatomic, strong) NSMutableArray *restoreIds;
//
@property (nonatomic, copy) charonTV_BoolBlock restoreBlock;
// apple後台商品
@property (nonatomic, strong) NSMutableArray *SKProducts;
@property (nonatomic, strong) NSNumberFormatter *formatter;
@property (nonatomic, strong) NSArray *lastTransactions;
@property (nonatomic, strong) NSString * order_no;
@property (nonatomic, strong) WSGoods * product;

@end
@implementation WSPurchaseManager
SingletonM

- (instancetype)init {
    self = [super init];
    if (self) {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        self.SKProducts = [[NSMutableArray alloc] init];
        self.formatter = [[NSNumberFormatter alloc] init];
        [self.formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
        [self.formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    }
    return self;
}

- (void)dealloc {
    // 解除监听
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

#pragma mark - Public
- (void)setProducts:(NSArray *)products {
    _products = products;
    NSMutableArray *array = [NSMutableArray array];
    for (WSGoods *goods in products) {
        BOOL has = NO;
        // 读取緩存
        for (SKProduct *item in self.SKProducts) {
            if ([item.productIdentifier isEqualToString:goods.ios_product_id]) {
                goods.SKProduct = item;
                [self.formatter setLocale:item.priceLocale];
                goods.priceLocale = [self.formatter stringFromNumber:@(item.price.floatValue)];
                has = YES;
                break;
            }
        }
        if (!has && goods.id) {
            [array addObject:goods.ios_product_id];
        }
    }
    // 請求对应的产品信息
    if (array.count > 0) {
        NSSet *productIdset = [NSSet setWithArray:array];
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdset];
        request.delegate = self;
        [request start];
    }
    else {
        if ([self.delegate respondsToSelector:@selector(didAppleReceiveResponse)]) {
            [self.delegate didAppleReceiveResponse];
        }
    }
}

// 发送购买請求
- (void)addProduct:(SKProduct *)product paymentId:(NSString *)paymentId {
    self.lastPaymentId = paymentId;
    if ([SKPaymentQueue canMakePayments]) {
        SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:product];
        payment.applicationUsername = WSSF(@"%ld", (long)appUserCenter.id);
        [[SKPaymentQueue defaultQueue] addPayment:payment];
        [self updateStatus:WSPurchaseStatusPaying object:nil];
    }
}

// 恢复购买
- (void)restoreWithIsChange:(Boolean)isChange block:(charonTV_BoolBlock)block {
    _restoreBlock = block;
    self.isRestore = !isChange;
    self.restoreIds = [[NSMutableArray alloc]init];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

#pragma mark - SKPaymentTransactionObserver
- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product {
    self.storeProductId = product.productIdentifier;
    
    return NO;
}

/** 监听购买结果 */
- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchased: // 支付完成
            {
                [self completeTransactions:@[transaction]];
            } break;
            case SKPaymentTransactionStateFailed:  // 支付失敗
            {
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                // 取消需要通知处理
                [self updateStatus:WSPurchaseStatusCancel object:nil];
            } break;
            case SKPaymentTransactionStateRestored: // 已经购买过该商品
            {
                if (!self.isRestore) {
                    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                }
            } break;
            case SKPaymentTransactionStatePurchasing: // 商品添加进列表
                
                break;
            default:
                [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
                break;
        }
        
    }
}

/** 苹果订单还原回调 */
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
    // 是否有相同类型的订单
    Boolean hasOrder = NO;
    NSMutableArray *restoreTransaction = [[NSMutableArray alloc] init];
    for (SKPaymentTransaction *transaction in queue.transactions) {
        if (transaction.originalTransaction && transaction.originalTransaction.transactionIdentifier.length > 0) {
            if (![self.restoreIds containsObject:transaction.originalTransaction.transactionIdentifier]) {
                [self.restoreIds addObject:transaction.originalTransaction.transactionIdentifier];
                [restoreTransaction addObject:transaction];
                hasOrder = YES;
                
            }
        }
    }
    // 兼容可能出现没有原始订单号的情况
    if (self.restoreIds.count == 0) {
        for (SKPaymentTransaction *transaction in queue.transactions) {
            if (transaction.transactionIdentifier) {
                [self.restoreIds addObject:transaction.transactionIdentifier];
            }
        }
    }
    if (self.isRestore) {
        self.lastPaymentId = nil;
        [self completeTransactions:restoreTransaction];
        for (SKPaymentTransaction *transaction in queue.transactions) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }
    }
}

#pragma mark - SKProductsRequestDelegate
/**
 收到iOS公司产品返回信息
 
 @param request request description
 @param response response description
 */
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    dispatch_async(dispatch_get_main_queue(), ^{
        // 返回值循環
        NSArray *array = response.products;
        for (NSInteger i = 0; i < array.count; i++) {
            SKProduct *product = array[i];
            // 存储数据到数组
            BOOL has = NO;
            for (SKProduct *item in self.SKProducts) {
                if ([item.productIdentifier isEqualToString:product.productIdentifier]) {
                    has = YES;
                }
            }
            if (!has) {
                [self.SKProducts addObject:product];
            }
            // 合并到自由商品对象
            for (WSGoods *goods in self.products) {
                if ([goods.ios_product_id isEqualToString:product.productIdentifier]) {
                    goods.SKProduct = product;
                    [self.formatter setLocale:product.priceLocale];
                    goods.priceLocale = [self.formatter stringFromNumber:@(product.price.floatValue)];
                    break;
                }
            }
        }
        if ([self.delegate respondsToSelector:@selector(didAppleReceiveResponse)]) {
            [self.delegate didAppleReceiveResponse];
        }
    });
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        [WSToast failureWithContent:error.localizedDescription];
    });
}

#pragma mark - 服务端验证交易
/** 服务端验证交易 */
- (void)verifyTransactionWithProductId:(NSString *)productId transactionId:(NSString *)transactionId isRestore:(BOOL)isRestore success:(charonTV_EmptyBlock)success failed:(void(^)(NSInteger statusCode))failed {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 从苹果服务读取
        NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
        if (!receiptData) { // 凭证丢失，不从支付队列中移除
            dispatch_async(dispatch_get_main_queue(), ^{
                if (failed) {
                    failed(-1);
                }
            });
            return;
        }
        WeakSelf
        NSString *receiptString = [receiptData base64EncodedStringWithOptions:0];
        
        [WSPurchaseRequest ordercharonTV_ValidWithOrder_no:self.order_no receipt_data:receiptString success:^{
            [WSToast dismiss];
            [weakSelf addTongJi];
            success();
        } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
            failed(error.code);
        }];
    });
}

/// 重新校验最后一次
- (void)retryVerifyTransaction {
    if (self.lastTransactions) {
        [self completeTransactions:self.lastTransactions];
    }
}

/** 充值成功回调 */
- (void)completeTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    self.lastTransactions = transactions;
    [self updateStatus:WSPurchaseStatusVerifing object:nil];
    __weak WSPurchaseManager *weakSelf = self;
    // 商品ID
    NSString *productId;
    if (transactions.lastObject.payment) {
        productId = transactions.lastObject.payment.productIdentifier;
    }
    if (!productId) {
        for (SKPaymentTransaction *transaction in transactions) {
            if (transaction.payment && transaction.payment.productIdentifier) {
                productId = transaction.payment.productIdentifier;
            }
        }
    }
    if (!productId) {
        productId = self.lastPaymentId;
    }
    if (!productId) {
        productId = @"productId is null";
    }
    
    // 订阅单号
    NSString *transactionId;
    if (self.isRestore) {
        transactionId = [self.restoreIds componentsJoinedByString:@","];
    }
    else {
        if (transactions.firstObject.originalTransaction && transactions.firstObject.originalTransaction.transactionIdentifier.length > 0) {
            transactionId = transactions.firstObject.originalTransaction.transactionIdentifier;
        }
        // 默认优先原始id
        if (!transactionId) {
            transactionId = transactions.firstObject.transactionIdentifier;
        }
    }
    // 没有id
    if (!transactionId) {
        transactionId = @"transactionIdentifier is null";
    }
    /// 結束掉堆積的未支付的訂單
    if (WSIsNullOrEmpty(self.order_no)) {
        for (SKPaymentTransaction *transaction in transactions) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }
        return;
    }
    __block NSString * pId = productId;
    [weakSelf verifyTransactionWithProductId:productId transactionId:transactionId isRestore:self.isRestore success:^{
        WSPurchaseStatus status = WSPurchaseStatusSuccess;
        weakSelf.lastTransactions = nil;
        for (SKPaymentTransaction *transaction in transactions) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }
        if ([pId containsString:@"Coins"]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:WSCoinsChangeNotification object:nil];
        }
        else {
            [[NSNotificationCenter defaultCenter]postNotificationName:WSVipChangeNotification object:nil];
        }
        [self updateStatus:status object:nil];
    } failed:^(NSInteger statusCode) {
        [weakSelf updateStatus:WSPurchaseStatusFailed object:transactions.lastObject];
        [weakSelf closeDebugSubscribeWithProductId:productId transactions:transactions];
    }];
}

// 更新UI状态(弹窗)
- (void)updateStatus:(WSPurchaseStatus)status object:(id)object {
    if ([self.delegate respondsToSelector:@selector(purchaseManager:updateStatus:object:)]) {
        [self.delegate purchaseManager:self updateStatus:status object:object];
    }
}

- (void)addTongJi{
    WeakSelf
    [[AppsFlyerLib shared] logEventWithEventName:AFEventPurchase
            eventValues: @{
              AFEventParamRevenue: @(self.product.price),
              AFEventParamCurrency: @"USD",
            }
            completionHandler:^(NSDictionary<NSString *,id> * _Nullable dictionary, NSError * _Nullable error){
                if(dictionary != nil) {
                    weakSelf.product = nil;
                    weakSelf.order_no = @"";
                    NSLog(@"In app callback success:");
                    for(id key in dictionary){
                        NSLog(@"Callback response: key=%@ value=%@", key, [dictionary objectForKey:key]);
                    }
                }
                if(error != nil) {
                    NSLog(@"In app callback error:%@", error);
                }
        }];
}

// 如果是测试環境關闭订阅相關订单
- (void)closeDebugSubscribeWithProductId:(NSString *)productId transactions:(NSArray<SKPaymentTransaction *> *)transactions {
#ifdef TEST_ON
    if ([self isSubscribeWithProductId:productId]) {
        for (SKPaymentTransaction *transaction in transactions) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }
    }
#endif
}

- (BOOL)isSubscribeWithProductId:(NSString *)productId {
    if ([productId containsString:@"Scriptwriter_Coins"] || [productId containsString:@"Scriptwriter_Day"]) {
        return NO;
    }
    return YES;
}

#pragma mark 生成订单
- (void)createOrderWithProduct:(WSGoods *)product {
    WeakSelf
    [WSToast loadingFull];
    [WSPurchaseRequest ordercharonTV_CreatWithGoods_id:product.id book_id:0 chapter_id:0 success:^(NSString *string) {
        if (WSIsNullOrEmpty(string)) {
            [WSToast simple:@"order_no is null"];
        }
        else {
            weakSelf.order_no = string;
            weakSelf.product = product;
            [weakSelf addProduct:product.SKProduct paymentId:product.ios_product_id];
        }
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}
@end
